﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Kovan.Library.Utils
{
    /// <summary>
    /// Cookie操作类
    /// </summary>
    public class KCookies
    {
        /// <summary>
        /// 设置Cookies
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetCookies(string domain, string name, string value)
        {

            HttpCookie cookie = new HttpCookie(name);//定义cookie对象
            DateTime dt = DateTime.Now;//定义时间对象
            TimeSpan ts = new TimeSpan(1, 0, 0, 0);//cookie有效作用时间，具体查msdn
            cookie.Expires = dt.Add(ts);//添加作用时间
            cookie.Value = HttpContext.Current.Server.UrlEncode(value);
            cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);

        }

        /// <summary>
        /// 设置Cookies
        /// </summary>
        /// <param name="domain">域</param>
        /// <param name="name">名称</param>
        /// <param name="value">值</param>
        /// <param name="ts">有效期</param>
        public static void SetCookies(string name, string value, TimeSpan ts)
        {

            HttpCookie cookie = new HttpCookie(name);//定义cookie对象
            if (ts.TotalDays >= 1)
            {
                cookie.Expires = DateTime.Now.Add(ts);//添加作用时间
            }
            cookie.Value = HttpContext.Current.Server.UrlEncode(value);
            //cookie.Domain = domain;
            //HttpContext.Current.Response.AppendCookie(cookie);
            HttpContext.Current.Response.Cookies.Add(cookie);

        }

        /// <summary>
        /// 获取Cookies
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCookies(string name)
        {
            string result = string.Empty;
            HttpCookie c = HttpContext.Current.Request.Cookies[name];
            if (c != null)
            {
                result = HttpContext.Current.Server.UrlDecode(c.Value);
            }
            return result;
        }

        /// <summary>
        /// 清空Cookies
        /// </summary>
        /// <param name="name"></param>
        public static void ClearCookies(string name)
        {
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[name];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
                cookie.Values.Clear();
                HttpContext.Current.Response.AppendCookie(cookie);
            }
        }
    }
}
